package com.insight.modules.ngalain.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

;


// 暂时注释掉，提高系统性能
//@Aspect   //定义一个切面
//@Configuration
public class LogRecordAspect {
    private static final Logger logger = LoggerFactory.getLogger(LogRecordAspect.class);

    /**
     * 定义切点，匹配com.insight.modules包下所有Controller类的所有public方法
     */
    @Pointcut("execution(public * com.insight.modules.*.*.*Controller.*(..))")
    public void excudeService() {
        // 切点方法，无需实现内容
    }

    /**
     * 环绕通知，记录请求开始和结束的信息
     *
     * @param pjp 切点连接点，表示被拦截的方法
     * @return 被拦截方法的返回结果
     * @throws Throwable 方法执行过程中抛出的异常
     */
    @Around("excudeService()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        // 获取当前请求对象
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) ra;
        HttpServletRequest request = sra.getRequest();

        // 获取请求相关信息
        String url = request.getRequestURL().toString();
        String method = request.getMethod();
        String uri = request.getRequestURI();
        String queryString = request.getQueryString();

        // 打印请求开始日志，包含URL、请求方法、URI、请求参数
        logger.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);

        // 执行被拦截的方法，并获取返回结果
        Object result = pjp.proceed();

        // 打印请求结束日志，包含方法返回值
        logger.info("请求结束，controller的返回值是 {}", result);

        return result;
    }
}

